/**
 *@描述：创建知识-知识产权的添加包编辑页面，其中包括设置知识权限、设置知识产权所有人等功能
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */

import {useEffect, useState} from 'react';
import {Button, Typography, Space, List, Card, Avatar, Popconfirm, message} from 'antd';
import {SaveOutlined, CheckOutlined, PlusOutlined, CloseOutlined} from '@ant-design/icons';

import {UserSelectorModal} from '@/components/UserSelector';

import classNames from 'classnames';
import {isEmpty} from 'lodash';

import styles from './style.less';
import {
    GetKnowledgeBaseInfoRequest,
    KnowledgeUserOwenRequest,
    PermissionSaveRequest
} from "@/pages/Dashboard/Knowledge/service";
import {useUpdateEffect} from "ahooks";
import CommonIconFont from "@/components/CommonIconFont";
import {connect} from "umi";
import {IndexModelState} from "@/pages/Dashboard/Knowledge/model";

const {Text} = Typography;
const IntellectualProperty = (
    {
        title,
        knowledgeId,
        setKnowledgeId,
        curSection,
        setCurSection,
        KnowledgeObj,
    }: {
        title: string;
        knowledgeId?: string;
        setKnowledgeId?: (val: string) => void;
        curSection: AircasKB.Knowledge.SectionItem;
        setCurSection?: (val: AircasKB.Knowledge.SectionItem) => void;
        KnowledgeObj: IndexModelState;
    }) => {

    //TODO：设置页面状态
    const [value, setValue] = useState<string>("0");
    const [peopleData, setPeopleData] = useState<AircasKB.UserItem[]>();
    const [loading, setLoading] = useState(false);

    //页面初始化时触发
    //TODO：userEffect函数
    useEffect(() => {
        if (!knowledgeId) {
            message.warn("请首先进入基本信息页面，填写基本信息！");
            setCurSection?.({
                id: 'basic',
                title: '基本信息'
            })
        } else {
            getKnowledgeUserOwen(knowledgeId);
            getKnowledgeBaseInfoRequest(knowledgeId);
        }
        // console.log(KnowledgeObj);
    }, [])//KnowledgeObj

    //页面重新渲染时触发
    //TODO：useUpdateEffect函数
    useUpdateEffect(() => {
        setCurSection?.(curSection);
    }, [curSection]);

    //根据知识ID获取当前知识的产权所有人列表，调用KnowledgeUserOwenRequest接口
    //TODO:根据知识ID获取当前知识的产权所有人列表
    const getKnowledgeUserOwen = (kid: string) => {
        kid && KnowledgeUserOwenRequest({
            knowledgeId: kid
        }).then((res) => {
            if (res.code == 200) {
                const result: AircasKB.UserItem[] = [];
                if (res.data.length > 0) {
                    res.data.map((item: any) => {
                        result.push({
                            userId: item.id,
                            name: {title: item.name},
                            picture: {
                                thumbnail: item.avatar || 'https://joeschmoe.io/api/v1/random',
                            }
                        })
                    })
                }
                setLoading(false);
                setPeopleData(result);
            } else {
                setLoading(false);
                setPeopleData([]);
            }
        })
    }

    //根据知识ID获取知识详情，此处仅永不获取isPublic参数，设置知识权限，调用GetKnowledgeBaseInfoRequest接口
    //TODO:根据知识ID获取知识详情，此处仅永不获取isPublic参数
    const getKnowledgeBaseInfoRequest = async (id: string) => {
        const res: AircasKB.ResponseType<AircasKB.Knowledge.GetKnowledgeBaseInfoResponse> = await GetKnowledgeBaseInfoRequest({
            id: id
        });
        if (res.code == 200) {
            // @ts-ignore
            setValue(res.data.isPublic);
        }
    }

    //权限列表
    const List: any[] = [
        {
            title: '授权查阅',
            description:
                '本条知识在本平台可以被检索，公开页面上仅显示标题、摘要等非主体信息，如需阅读下载完整版本，需获得知识产权所有人授权方可继续。',
            value: "0",
        },
        {
            title: '公开发布',
            description: '本条知识完全公开，包括匿名用户在内的所有用户可以免费阅读下载。',
            value: "1",
        },
        {
            title: '仅限会员',
            description: '本条知识在本平台内完全公开，仅限本平台用户内登录后免费阅读下载。',
            value: "2",
        },

    ];

    //保存按钮触发事件
    //TODO：保存按钮触发事件
    const handleSubmit = (e: any) => {
        setLoading(true);
        const ownerIds: any[] = [];
        peopleData?.map((item) => {
            ownerIds.push(item.userId);
        })

        //设置保存需要的请求参数
        const requestParams: AircasKB.Knowledge.PermissionSaveRequestParams = {
            knowledgeId: knowledgeId,
            ownerIds: ownerIds,
            permissionType: value
        }
        // console.log(requestParams);
        //调用PermissionSaveRequest接口，保存知识产权所设置的信息
        PermissionSaveRequest(requestParams).then(res => {
            if (res.code == 200) {
                setLoading(false);
                message.success("保存成功！");
                setKnowledgeId?.(res.data.knowledgeId);
            } else {
                setLoading(false);
                message.error("保存失败！");
            }
        });
    }

    return (
        <div className={styles.wrapper}>
            <div className={styles.subTitle}>
                <Text>知识产权</Text>
            </div>
            <p className={styles.label}>是否公开：</p>
            <div className={styles.formControl}>
                {List.map((item: any, index: number) => {
                    return (
                        <CustomRadio
                            key={index}
                            title={item.title}
                            description={item.description}
                            value={item.value}
                            checked={item.value === value}
                            onChecked={setValue}
                        />
                    );
                })}
            </div>
            <p className={styles.label}>产权所有人：</p>
            <div className={styles.formControl}>
                <PeopleCard peopleData={peopleData} setPeopleData={setPeopleData} knowledgeId={knowledgeId}/>
            </div>
            <div style={{margin: '20px 0'}}>
                <Button size="large" type="primary" htmlType="submit" loading={loading}
                        icon={<SaveOutlined/>} onClick={handleSubmit}>
                    保存
                </Button>
            </div>
        </div>
    );
};

const CustomRadio = ({
                         title,
                         description,
                         value,
                         checked,
                         onChecked,
                     }: {
    title: string;
    description?: string;
    value: number;
    checked: boolean;
    onChecked?: (val: string) => void;
}) => {
    return (
        <Space
            className={classNames(styles.customRadio, {
                [styles.active]: checked,
            })}
            align="start"
            onClick={() => onChecked?.(value.toString())}
        >
            <div className={styles.radio}>{checked && <CheckOutlined/>}</div>
            <div className={styles.content}>
                <Text className={styles.title}>{title}</Text>
                <Text className={styles.description}>{description}</Text>
            </div>
        </Space>
    );
};

const PeopleCard = (
    {
        knowledgeId,
        peopleData,
        setPeopleData,
    }: {
        knowledgeId?: string;
        peopleData?: AircasKB.UserItem[];
        setPeopleData?: (val: AircasKB.UserItem[]) => void;
    }
) => {
    const [showUserSelectorModal, setShowUserSelectorModal] = useState<boolean>(false);
    useEffect(() => {
        setPeopleData?.(peopleData || []);
    }, [peopleData])

    const doRemove = async (obj: AircasKB.UserItem) => {
        //TODO 删除
        const result = delObj({
            list: peopleData || [],
            data: obj
        });
        setPeopleData?.(result);
        // setPeopleData1?.(result);
    };

    const delObj = ({
                        list,
                        data
                    }: {
        list: AircasKB.UserItem[];
        data: AircasKB.UserItem;
    }): AircasKB.UserItem[] => {
        let index = -1;
        for (let i = 0; i < list.length; i++) {
            if (list[i].userId == data.userId) {//目前主键和想要删除的主键对比
                index = i;
            }
        }
        if (index > -1) {
            list.splice(index, 1);
        }
        return list;
    }

    return (
        <>
            <List
                className={styles.cardList}
                grid={{gutter: 16, column: 4}}
                // loading={loading}
                itemLayout="vertical"
                dataSource={peopleData && peopleData.concat({})}
                renderItem={(item) => (
                    <List.Item>
                        {!isEmpty(item.name) && (
                            <Card className={styles.item} bodyStyle={{padding: 10}}>
                                <List.Item.Meta
                                    avatar={<Avatar src={item.picture?.thumbnail

                                    } icon={
                                        <CommonIconFont
                                            // @ts-ignore
                                            type={`aircaskb-touxiang`}
                                            style={{fontSize: 32}}
                                        />
                                    }/>}

                                    title={<a>{item.name?.title}</a>}
                                    description="空天信息创新研究院"
                                />
                                <Popconfirm
                                    title="确认删除吗？"
                                    okText="确定"
                                    cancelText="取消"
                                    onConfirm={() => doRemove(item)}
                                >
                                    <Button
                                        className={styles.removeBtn}
                                        size="small"
                                        type="link"
                                        danger
                                        icon={<CloseOutlined/>}
                                    ></Button>
                                </Popconfirm>
                            </Card>
                        )}
                        {isEmpty(item.name) && (
                            <div
                                className={styles.addBtn}
                                onClick={() => setShowUserSelectorModal(true)}
                            >
                                <Button type="link" size="large" icon={<PlusOutlined/>}>
                                    添加
                                </Button>
                            </div>
                        )}
                    </List.Item>
                )}
            />
            {showUserSelectorModal && (
                <UserSelectorModal
                    show={showUserSelectorModal}
                    onSelect={(user: AircasKB.UserItem) => {
                        setShowUserSelectorModal(false);
                        // @ts-ignore
                        setPeopleData?.([...peopleData, user]);
                    }}
                    onCancel={() => setShowUserSelectorModal(false)}
                ></UserSelectorModal>
            )}
        </>
    );
};
// @ts-ignore
const mapStateToProps = ({KnowledgeObj}) => {
    return {
        KnowledgeObj
    };

}

export default connect(mapStateToProps)(IntellectualProperty);
